import { constantRoutes } from '@/router'
import {getMenuList} from "@/api/user";
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 * 判断当前用户是否拥有该角色下的路由菜单权限
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 * 过滤出拥有的菜单信息
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    //判断是否拥有相应的权限
    if(hasPermission(roles,tmp)){
      //获取该路由对应的组件
      let component = tmp.component;
      //判断是否拥有相应的根组件
      if(route.component){
        //是否是根组件
        if(component === 'Layout'){
          tmp.component = Layout;
        }else{
          //获取对应的具体的组件信息，异步加载resolve即为promise的resolve,组件加载成功之后再调用
          tmp.component = (resolve) => require([`@/views${component}`],resolve);
        }
      }
    }

    //是否有子菜单
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  //生成路由
  generateRoutes({ commit }, roles) {
    return new Promise((resolve,reject) => {
      //查询菜单
      getMenuList().then(res => {
        //存放对应权限路由信息
        let accessedRoutes;
        if(res.code == 200){
          accessedRoutes = filterAsyncRoutes(res.data,roles);
        }
        //将路由信息保存到store中
        commit('SET_ROUTES',accessedRoutes);
        resolve(accessedRoutes);
      }).catch(error => {
        reject(error);
      });
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
